var controllersModule = angular.module('app.controllers');
require('underscore');

/**
 * @ngInject
 */
function EmployeesCtrl(toastr, $uibModal, $filter, employeesResource) {
    var vm = this;

    vm.title = $filter('translate')('employees');

    vm.employees = [];
    vm.displayedemployees = [];

    employeesResource.getAll(function(res) {
        vm.employees = res;
        vm.displayedEmployees = [].concat(vm.employees);
    });

    vm.addEmp = function() {
        vm.empModel = {
            FirstName: '',
            LastName: '',
            Email: '',
            EmpNumber: 1
        };

        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'addEmpModal.html',
            controller: 'addEmpModal',
            size: 'lg',
            resolve: {
                empModel: function() {
                    return vm.empModel;
                }
            }
        });

        modalInstance.result.then(function () {
            employeesResource.save(vm.empModel, function(res) {
                vm.employees.push(res);
                toastr.success($filter('translate')('empAddMsg'));
            });
        }, function () {
            vm.empModel = {};
        });
    };

    vm.editEmp = function(empModel) {
        var editedEmpModel = angular.copy(empModel);

        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'addEmpModal.html',
            controller: 'addEmpModal',
            size: 'lg',
            resolve: {
                empModel: function() {
                    return editedEmpModel;
                }
            }
        });

        modalInstance.result.then(function () {
            employeesResource.save(editedEmpModel, function(res) {
                var newEmp = res;
                var oldEmp = _.findWhere(vm.employees, {Id: newEmp.Id});
                angular.extend(oldEmp, newEmp);
                toastr.success($filter('translate')('empEditMsg'));
            });
        });
    };

    vm.delEmp = function(empModel) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'confirmationModal.html',
            controller: 'confirmationModal',
            size: 'sm',
            resolve: {
                title: function() { return $filter('translate')('delItem'); },
                content: function() { return $filter('translate')('delConfirmationMsg'); }
            }
        });

        modalInstance.result.then(function() {
            employeesResource.remove(empModel, function() {
                vm.employees = _.without(vm.employees, empModel);
                toastr.success($filter('translate')('empDelMsg'));
            });
        });
    };
}

controllersModule.controller('EmployeesCtrl', EmployeesCtrl);
